﻿using BLL;
using DAL;
using MathNet.Numerics.LinearAlgebra.Factorization;
using Model;
using Newtonsoft.Json;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Tools;
using 后整理管理系统.BLL;
using 后整理管理系统.自定义类;
using 后整理管理系统.选择窗体;
using 纺织贸易管理系统.其他窗体;
using 纺织贸易管理系统.自定义类;
using 纺织贸易管理系统.设置窗体;
using 纺织贸易管理系统.选择窗体;

namespace 纺织贸易管理系统.新增窗体
{
    public partial class 流转卡 : Form
    {
        public FormUseful Useful { get; set; }
        public Liuzhuancard liuzhuancard { get; set; } = new Liuzhuancard();
        private List<StockTable> stocks = new List<StockTable>();
        List<liuzhuanmingxi> liuzhuangkamingxi = new List<liuzhuanmingxi>();
        public List<danjumingxitable> danjumingxis { get; set; } = new List<danjumingxitable>();
        private int rowindex;
        public DanjuTable danju { get; set; } = new DanjuTable();
        private List<int> SelectIndex = new List<int>();
        private Boolean IsNeedPrint = true;
        private List<ImportAndExportOfRawMaterials> RawMaterials = new List<ImportAndExportOfRawMaterials>();
        public 流转卡()
        {
            InitializeComponent();
            cmbmoban.DataSource = Tools.获取模板.获取所有模板(PrintPath.唛头模板);
            EmployerHelper.AssignmentCombox(cmbGongyizhidingren);
            uiDatePicker1.Value = DateTime.Now;
            cmbjitai.Items.AddRange(MachineTableService.GetMachineTablelst("select * from machinetable").Select(x => x.MachineID).ToArray());
            cmblianxiren.Items.AddRange(YuanGongTableService.GetYuanGongTablelst().Select(x => x.Xingming).ToArray());
            CreateGrid.Create(this.Name, gridView2);
            CreateGrid.Create("原料入库单", gridView3, "gridView1");
            try
            {
                gridView3.Columns["Num"].ColumnEdit = RawBtn;
                gridView2.Columns["Bianhao"].ColumnEdit = ButtonEdit1;
                gridView2.Columns["pingming"].ColumnEdit = ButtonEdit1;
                gridView2.Columns["danwei"].ColumnEdit = cmddanwei;
                gridView2.Columns["yanse"].ColumnEdit = colorbtn;
                gridView2.Columns["ColorNum"].ColumnEdit = colorbtn;
                gridView2.IndicatorWidth = 30;
               
                gridView2.OptionsCustomization.AllowFilter = false;
            }
            catch
            {
                配置列ToolStripMenuItem_Click(null, null);
            }
            gridControl2.DataSource = danjumingxis;
            gridControl1.DataSource = liuzhuangkamingxi;
            打ToolStripMenuItem.SelectedIndex = 0;
            var conMenu = new ContexMenuEX() { formName = this.Name, gridControl = gridControl2, gridView = gridView2, menuStrip = contextMenuStrip2 };
            conMenu.Init();
            打ToolStripMenuItem.Text = SettingService.GetSetting(new Model.Setting() { formname = "", settingname = "流转卡样式", settingValue = "样式一" }).settingValue;
        }
        private void 流转卡_Load(object sender, EventArgs e)
        {
            InitForm();
        }
        private void InitForm()
        {
            SelectIndex.Clear();
            if (Useful == FormUseful.复制)
            {
                txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.流转卡, uiDatePicker1.Value, DanjuLeiXing.流转卡);
                txtkehu.Text = danju.ksmc;
                var customer = LXRService.GetOneLXR(x => x.MC == danju.ksmc);
                cmbmoban.Text = MaitouService.GetOneMaitou(x => x.khbh == customer.BH).path;
                cmbdanwei.Text = customer.Danwei;
                txtmashu.Text = customer.Mashu.ToString("N0");
                var fabric=Connect.dbcontext.Queryable<db>().First(x=>x.bh== danjumingxis[0].Bianhao);
                if (fabric != null)
                {
                    txtmashu.Text =  fabric.HangingCode==0?"100":fabric.HangingCode.ToString();
                }
                
                txtkezhong.Text = danjumingxis.Count > 0 ? danjumingxis[0].kezhong : string.Empty;
                txtmenfu.Text = danjumingxis.Count > 0 ? danjumingxis[0].menfu : string.Empty;
                txtpingming.Text = danjumingxis.Count > 0 ? danjumingxis[0].pingming : string.Empty;
                txtckmc.Text = danju.ckmc;
                txtbeizhu.Text = danju.bz;
                cmbJincangyuanying.Text = danju.jiagongleixing;
                txtshuliang.Text = danjumingxis.Sum(x => x.chengpingmishu).ToString();
                txtyanse.Text = danjumingxis.Count > 0 ? danjumingxis[0].yanse : string.Empty;
                cmbfrontorblack.Text = string.Empty;
                cmbLevel.Text = "一般";
                if (customer != null)
                {
                    txtRemarkers.Text = customer.bz;
                }
                cmbGongyizhidingren.Text = string.Empty;
                TxtBaseFabricColor.Text = string.Empty;
                txtIncomingaddress.Text =danju.fromDanhao ;
                var gongyis = TechnologyTableService.GetTechnologyTablelst("select * from Technologytable");
                foreach (var g in gongyis)
                {
                    liuzhuangkamingxi.Add(new liuzhuanmingxi() { CardNum = txtdanhao.Text, GongyiYaoqiu = g.Technology, Cishu = 1 });
                }
                //danjumingxis.AddRange(new danjumingxitable[30] );            
                var count = danjumingxis.Count;
                foreach (var item in danjumingxis)
                {
                    item.chengpingmishu = item.chengpingmishu -item.ProducedQuantity==0?item.chengpingmishu : item.chengpingmishu - item.ProducedQuantity;
                    item.danhao = txtdanhao.Text;
                }
                for (int i = 0; i < 30 - count; i++)
                {
                    danjumingxis.Add(new danjumingxitable { danhao = txtdanhao.Text });
                }

                gridControl1.RefreshDataSource();
                gridControl2.DataSource = danjumingxis;
                uiDatePicker1.Enabled = true;
                dateTimePicker1.Value= uiDatePicker1.Value.AddDays(4);
            }
            else
            {
                if (Useful == FormUseful.修改)
                {
                    Edit();
                }
                else
                {
                    if (Useful == FormUseful.新增)
                    {
                        txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.流转卡, uiDatePicker1.Value, DanjuLeiXing.流转卡);
                        txtbeizhu.Text = "";
                        txtkehu.Text = "";
                        txtkezhong.Text = string.Empty;
                        txtmenfu.Text = string.Empty;
                        txtpingming.Text = string.Empty;
                        txtckmc.Text = string.Empty;
                        txtshuliang.Text = danjumingxis.Sum(x => x.chengpingmishu).ToString();
                        txtyanse.Text = danjumingxis.Count > 0 ? danjumingxis[0].yanse : string.Empty; ;
                        liuzhuangkamingxi.Clear();
                        uiDatePicker1.Enabled = true;
                        dateTimePicker1.Value= uiDatePicker1.Value.AddDays(4);
                        cmbfrontorblack.Text = string.Empty;
                        cmbLevel.Text = "一般";
                        var customer = Connect.dbcontext.Queryable<LXR>().First(x => x.MC == txtkehu.Text);
                        if (customer != null)
                        {
                            txtRemarkers.Text =customer.bz;
                        }
                        if (danjumingxis.Count > 0)
                        {
                            var fabric = Connect.dbcontext.Queryable<db>().First(x => x.bh == danjumingxis[0].Bianhao);
                            if (fabric != null)
                            {
                                txtmashu.Text = fabric.HangingCode == 0 ? "100" : fabric.HangingCode.ToString();
                            }
                        }
                        cmbGongyizhidingren.Text=string.Empty;
                        TxtBaseFabricColor.Text = string.Empty;
                        txtIncomingaddress.Text = string.Empty;
                        var gongyis = TechnologyTableService.GetTechnologyTablelst("select * from Technologytable");
                        liuzhuangkamingxi.Clear();
                        foreach (var g in gongyis)
                        {
                            liuzhuangkamingxi.Add(new liuzhuanmingxi() { CardNum = txtdanhao.Text, GongyiYaoqiu = g.Technology, Cishu = 1 });
                        }
                        //danjumingxis.AddRange(new danjumingxitable[30] );            
                        danjumingxis.Clear();
                        var count = danjumingxis.Count;
                        for (int i = 0; i < 30 - count; i++)
                        {
                            danjumingxis.Add(new danjumingxitable { danhao = txtdanhao.Text });
                        }

                        gridControl3.DataSource = RawMaterials;
                        gridControl2.DataSource = danjumingxis;
                        gridControl1.DataSource = liuzhuangkamingxi;
                        gridControl2.RefreshDataSource();
                    }
                    else
                    {
                        if (Useful == FormUseful.查看)
                        {
                            Edit();
                            新增ToolStripMenuItem.Enabled = false;
                            gridView1.OptionsBehavior.Editable= false;
                            gridView2.OptionsBehavior.Editable = false;
                            gridView3.OptionsBehavior.Editable = false;
                            foreach (Control c in this.UiGroup2.Controls)
                            {
                               c.Enabled = false;
                            }
                            txtdanhao.Enabled = true;
                            gridView2.OptionsBehavior.Editable = false;
                            gridView1.OptionsBehavior.Editable = false;
                            gridView3.OptionsBehavior.Editable = false;
                        }
                    }
                }
            }
            RawMaterials.Clear();
            RawMaterials = Connect.CreatConnect().Query<ImportAndExportOfRawMaterials>(x => x.DocNum == txtdanhao.Text);
            var length = RawMaterials.Count;
            for (int i = 0; i < 30 - length; i++)
            {
                RawMaterials.Add(new ImportAndExportOfRawMaterials() { DocNum = txtdanhao.Text });
            }
            gridControl3.DataSource = RawMaterials;
            IsNeedPrint = true;
        }
        private void Edit()
        {
            txtdanhao.Text = liuzhuancard.CardNum;
            txtbeizhu.Text = liuzhuancard.Beizhu;
            txtkehu.Text = liuzhuancard.Customer;
            txtkezhong.Text = liuzhuancard.Kezhong;
            txtmenfu.Text = liuzhuancard.Menfu;
            txtpingming.Text = liuzhuancard.Pingming;
            txtshuliang.Text = liuzhuancard.Shuliang.ToString();
            txtyanse.Text = liuzhuancard.Color;
            txtckmc.Text = liuzhuancard.StockName;
            cmbJincangyuanying.Text = liuzhuancard.JiaGongYuanYing;
            uiDatePicker1.Enabled = false;
            dateTimePicker1.Value = liuzhuancard.LatestDeliverydate;
            cmbdanwei.Text = liuzhuancard.Unit;
            cmbmoban.Text = liuzhuancard.ShippingMark;
            txtmashu.Text = liuzhuancard.MaShu.ToString();
            cmbfrontorblack.Text = liuzhuancard.FrontOrBack;
            txtRemarkers.Text = liuzhuancard.Remarlers;
            cmbGongyizhidingren.Text = liuzhuancard.ProcessDeveloper;
            TxtBaseFabricColor.Text = liuzhuancard.BaseFabricColor;
            txtIncomingaddress.Text = liuzhuancard.IncomingAddress;
            txtCeshizhibiao.Text = liuzhuancard.TestMetrics;
            txtChengpingyaoqiu.Text = liuzhuancard.FinishedProductRequirements;
            txtdanbumenfu.Text = liuzhuancard.SingleClothWidth;
            txtdanbukezhong.Text = liuzhuancard.SingleClothWeight;
            txtDanbufangshui.Text = liuzhuancard.SingleClothWatertight;
            txtdibukezhong.Text = liuzhuancard.BottomClothWeight;
            txtshuixi.Text = liuzhuancard.Washing;
            txtshuiya.Text = liuzhuancard.Hydraulic;
            txttousi.Text =liuzhuancard. MoisturePermeability;
            cmbLevel.Text = liuzhuancard.UrgencyLevel;
            //var gongyis = TechnologyTableService.GetTechnologyTablelst("select * from Technologytable");
            //foreach (var g in gongyis)
            //{
            //    liuzhuangkamingxi.Add(new liuzhuanmingxi() { CardNum = txtdanhao.Text, GongyiYaoqiu = g.Technology, Cishu = 1, Beizhu = "" });
            //}
            liuzhuangkamingxi = liuzhuanmingxiService.Getliuzhuanmingxilst(x => x.CardNum == txtdanhao.Text);
            //foreach (var m in mingxis)
            //{
            //    var z = liuzhuangkamingxi.Where(x => x.GongyiYaoqiu == m.GongyiYaoqiu).ToList().Count > 0 ? liuzhuangkamingxi.Where(x => x.GongyiYaoqiu == m.GongyiYaoqiu).ToList()[0] : new liuzhuanmingxi();
            //    z.Cishu = m.Cishu;
            //    z.Beizhu = m.Beizhu;
            //    z.MachineID = m.MachineID;
            //}
            gridControl1.DataSource = liuzhuangkamingxi;
            gridControl1.RefreshDataSource();
            danjumingxis = danjumingxitableService.Getdanjumingxitablelst(x => x.danhao == txtdanhao.Text);
            var count = danjumingxis.Count;
            for (int i = 0; i < 30 - count; i++)
            {
                danjumingxis.Add(new danjumingxitable { danhao = txtdanhao.Text });
            }

            gridControl2.DataSource = danjumingxis;
            gridControl2.RefreshDataSource();
        }
        private void 选择布料ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 工序选择();
            fm.ShowDialog();
            txtbeizhu.Text = string.Empty;
            liuzhuangkamingxi.Clear();
            foreach (var t in fm.technologyTables)
            {
                if (QueryTime.自动填写工序 == "是")
                {
                    txtbeizhu.Text += t.Technology + "+";
                }
                liuzhuangkamingxi.Add(new liuzhuanmingxi() { CardNum = txtdanhao.Text, Cishu = 1, GongyiYaoqiu = t.Technology, _date = uiDatePicker1.Value });
            }
            if (!string.IsNullOrEmpty(txtbeizhu.Text))
            {
                txtbeizhu.Text = txtbeizhu.Text.Substring(0, txtbeizhu.Text.Length - 1);
            }
            gridControl1.RefreshDataSource();
        }

        private void 打印编辑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (后整理管理系统.自定义类.PrintService.CheckPrintDesignAccess())
            {
                Printer(PrintModel.Design);
            }
        }
        /// <summary>
        /// 校验是否重复开卡和没有库存开卡
        /// </summary>
        /// <returns></returns>
        private Boolean CheckMingxi()
        {
            if (Useful == FormUseful.新增)
            {
                foreach (var m in danjumingxis.Where(x => !string.IsNullOrWhiteSpace(x.pingming)).ToList())
                {
                   if( Connect.dbcontext.Queryable<StockTable>().Any(x => x.RKDH == m.rkdh && x.GH == m.ganghao  
                    && x.PM == m.pingming&&x.YS==m.yanse))
                 
                    {
                        var message = $"缸号为:{m.ganghao}\r\n品名为:{m.pingming}\r\n颜色为:{m.yanse}\r\n入库单号为:{m.rkdh}\r\n没有找到该布料在库存中的信息,打印失败";
                        ShowMessageBox.ShowErrorBox(message);
                        return false;
                    }
                   
                }
            }
            return true;
        }
        private void Printer(PrintModel printModel)
        {
            gridView1.CloseEditor();
            if (SaveRules() == false)
            {
                return;
            }
            var fs = new FastReport.Report();
            DataTable liuzhuandan = new DataTable("流转单信息");
            liuzhuandan.Columns.Add("流转卡号");
            liuzhuandan.Columns.Add("客户名称");
            liuzhuandan.Columns.Add("日期", typeof(DateTime));
            liuzhuandan.Columns.Add("品名");
            liuzhuandan.Columns.Add("克重");
            liuzhuandan.Columns.Add("门幅");
            liuzhuandan.Columns.Add("颜色");
            liuzhuandan.Columns.Add("数量", typeof(decimal));
            liuzhuandan.Columns.Add("备注");
            liuzhuandan.Columns.Add("开卡人");
            liuzhuandan.Columns.Add("唛头模板");
            liuzhuandan.Columns.Add("唛头单位");
            liuzhuandan.Columns.Add("打卷码数");
            liuzhuandan.Columns.Add("正反面");
            liuzhuandan.Columns.Add("流转卡备注");
            liuzhuandan.Columns.Add("工艺制定人");
            liuzhuandan.Columns.Add("底布颜色");
            liuzhuandan.Columns.Add("来货地址");
            liuzhuandan.Columns.Add("单布门幅");
            liuzhuandan.Columns.Add("单布克重");
            liuzhuandan.Columns.Add("单布防水");
            liuzhuandan.Columns.Add("测试指标");
            liuzhuandan.Columns.Add("成品要求");
            liuzhuandan.Columns.Add("底布克重");
            liuzhuandan.Columns.Add("水洗");
            liuzhuandan.Columns.Add("水压");
            liuzhuandan.Columns.Add("透湿");
            liuzhuandan.Columns.Add("交期",typeof(DateTime));
            liuzhuandan.Columns.Add("着急程度");
            liuzhuandan.Rows.Add();
            //赋值
            liuzhuandan.Rows[0]["流转卡号"] = txtdanhao.Text;
            liuzhuandan.Rows[0]["客户名称"] = txtkehu.Text;
            liuzhuandan.Rows[0]["日期"] = uiDatePicker1.Value;
            liuzhuandan.Rows[0]["唛头模板"] = cmbmoban.Text;
            liuzhuandan.Rows[0]["唛头单位"] = cmbdanwei.Text;
            liuzhuandan.Rows[0]["打卷码数"] = txtmashu.Text;
            liuzhuandan.Rows[0]["品名"] = txtpingming.Text;
            liuzhuandan.Rows[0]["克重"] = txtkezhong.Text;
            liuzhuandan.Rows[0]["门幅"] = txtmenfu.Text;
            liuzhuandan.Rows[0]["颜色"] = txtyanse.Text;
            liuzhuandan.Rows[0]["正反面"] = cmbfrontorblack.Text;
            liuzhuandan.Rows[0]["数量"] = Convert.ToDecimal(txtshuliang.Text);
            liuzhuandan.Rows[0]["开卡人"] = Tools.CurrentUser.user.YHMC;
            liuzhuandan.Rows[0]["备注"] = cmbJincangyuanying.Text == "首次加工" ? txtbeizhu.Text : cmbJincangyuanying.Text + " " + txtbeizhu.Text;
            liuzhuandan.Rows[0]["流转卡备注"] = txtRemarkers.Text;
            liuzhuandan.Rows[0]["工艺制定人"] = cmbGongyizhidingren .Text;
            liuzhuandan.Rows[0]["底布颜色"] = TxtBaseFabricColor.Text;
            liuzhuandan.Rows[0]["来货地址"] = txtIncomingaddress.Text;
            liuzhuandan.Rows[0]["单布门幅"] =txtdanbumenfu.Text;
            liuzhuandan.Rows[0]["单布克重"] = txtdanbukezhong.Text;
            liuzhuandan.Rows[0]["单布防水"] = txtDanbufangshui.Text;
            liuzhuandan.Rows[0]["测试指标"] = txtCeshizhibiao.Text;
            liuzhuandan.Rows[0]["成品要求"] = txtChengpingyaoqiu.Text;
            liuzhuandan.Rows[0]["底布克重"] = txtdibukezhong.Text;
            liuzhuandan.Rows[0]["水洗"] = txtshuixi.Text;
            liuzhuandan.Rows[0]["水压"] = txtshuiya.Text;
            liuzhuandan.Rows[0]["透湿"] = txttousi.Text;
            liuzhuandan.Rows[0]["交期"] = dateTimePicker1.Value ;
            liuzhuandan.Rows[0]["着急程度"] = cmbLevel.Text;
            //
            DataSet ds = new DataSet();
            ds.Tables.Add(liuzhuandan);
            ///明细
            DataTable mingxi = new DataTable("流转卡明细");
            try
            {
                for (var col = 0; col < gridView1.Columns.Count; col++)
                {
                    mingxi.Columns.Add(gridView1.Columns[col].Caption);
                }
                //明细赋值
                for (var row = 0; row < gridView1.RowCount; row++)
                {
                    var index = mingxi.Rows.Add();
                    for (var col = 0; col < gridView1.Columns.Count; col++)
                    {
                        index[col] = gridView1.GetRowCellValue(row, gridView1.Columns[col].FieldName);
                    }
                }

                ds.Tables.Add(mingxi);
                ////布料信息
                ///明细
                DataTable bulioaos = new DataTable("布料明细");
                for (var col = 0; col < gridView2.Columns.Count; col++)
                {
                    bulioaos.Columns.Add(gridView2.Columns[col].Caption);
                }
                //布料明细赋值
                foreach (var row in SelectIndex.Distinct())
                {
                    if (!string.IsNullOrWhiteSpace(gridView2.GetRowCellValue(row, "pingming").ToString()))
                    {
                        var index = bulioaos.Rows.Add();
                        for (var col = 0; col < gridView2.Columns.Count; col++)
                        {
                            index[col] = gridView2.GetRowCellValue(row, gridView2.Columns[col].FieldName);
                        }
                    }
                }
                ds.Tables.Add(bulioaos);
                ds.Tables.Add(CreateGongyiTable());
                var rawdt = JsonConvert.DeserializeObject<DataTable>(JsonConvert.SerializeObject(RawMaterials.Where(x => !string.IsNullOrEmpty(x.Num))));
                rawdt.TableName = "原料信息";
                ds.Tables.Add(rawdt);
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox (  ex.Message);
            }
            fs.RegisterData(ds);
            var path = 打ToolStripMenuItem.SelectedIndex == 0? Application.StartupPath + "\\Report\\流转单.frx": Application.StartupPath + "\\Report\\流转单1.frx";
          
           
            if (File.Exists(path))
            {
                fs.Load(path);
            }
            else
            {
                fs.Design();
                var arr = path.Split('\\');
                ReportTableService.DeleteReportTable(x => x.reportName == arr[arr.Length - 1] && x.reportStyle == ReportService.报表);
                ReportService.LoadReport(path, new ReportTable { reportStyle = ReportService.报表, reportName = arr[arr.Length - 1] });
                return;
            }
            try
            {
                switch (printModel)
                {
                    case PrintModel.Design:
                        fs.Design();
                        var arr = path.Split('\\');
                        ReportTableService.DeleteReportTable(x => x.reportName == arr[arr.Length - 1] && x.reportStyle == ReportService.报表);
                        ReportService.LoadReport(path, new ReportTable { reportStyle = ReportService.报表, reportName = arr[arr.Length - 1] });
                        break;
                    case PrintModel.Privew:
                        fs.Show();
                        break;
                    case PrintModel.Print:
                        fs.Print();
                        break;
                }
            }
            catch
            {
                fs.Design();
            }
            IsNeedPrint=false;
            if (Useful != FormUseful.查看)
            {
                Save();
            }
        }
        private void Save()
        {
            try
            {
                using (var trans = Connect.dbcontext.UseTran())
                {
                    var resmingxis = GetResMingxi();
                    //Connect.dbcontext.BeginTran();
                    if (Useful == FormUseful.修改)
                    {
                        foreach (var m in resmingxis.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList())
                        {
                            if (JuanHaoTableService.GetJuanHaoTablelst(x => x.CustomerPingMing == txtdanhao.Text && x.SampleName == m.pingming && x.yanse == m.yanse && x.GangHao == m.ganghao).Count > 0)
                            {
                                if (!Sunny.UI.UIMessageBox.ShowAsk("该单据已经有对应的打卷信息！\r\n是否继续开卡？"))
                                { return; }
                            }
                        }
                        流转单BLL.修改(CreateNewDoc(), GetLiuzhuanmingxis(), stocks, resmingxis.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList(), RawMaterials);
                    }
                    else
                    {

                        流转单BLL.保存(CreateNewDoc(), GetLiuzhuanmingxis(), stocks, resmingxis.Where(x => !string.IsNullOrEmpty(x.pingming)).ToList(), RawMaterials);
                    }
                    trans.CommitTran();
                    Continue();
                }
            }
            catch (Exception ex)
            {
                ShowMessageBox.ShowErrorBox(ex.Message);
                return;
            }
        }
        private DataTable CreateGongyiTable()
        {
            var dt = new DataTable();
            dt.TableName = "工艺名称";

            foreach (var g in Connect.dbcontext.Queryable<TechnologyTable>().ToList())
            {
                dt.Columns.Add(g.Technology);
            }
            dt.Rows.Add();
            foreach (var g in Connect.dbcontext.Queryable<TechnologyTable>().ToList())
            {
                if (liuzhuangkamingxi.FirstOrDefault(x => x.GongyiYaoqiu == g.Technology) != null)
                {
                    dt.Rows[0][g.Technology] = liuzhuangkamingxi.FirstOrDefault(x => x.GongyiYaoqiu == g.Technology).Beizhu;
                }
            }
            return dt;
        }
        private void 打印预览ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Printer(PrintModel.Privew);
        }

        private void 直接打印ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Useful == FormUseful.新增)
            {
                Sunny.UI.UIMessageBox.ShowInfo("新增状态下不能直接打印！\r\n只有修改状态下可直接打印\r\n需要按保存后提示打印！");
                return;
            }
            Printer(PrintModel.Print);
        }
        private Liuzhuancard CreateNewDoc()
        {
           return   new Liuzhuancard()
            {
                Beizhu = txtbeizhu.Text,
                CardNum = txtdanhao.Text,
                Card_Date = uiDatePicker1.Value,
                Color = txtyanse.Text,
                Customer = txtkehu.Text,
                Ganghao = string.Empty,
                Kezhong = txtkezhong.Text,
                Menfu = txtmenfu.Text,
                Pingming = txtpingming.Text,
                StockName = txtckmc.Text,
                JiaGongYuanYing = cmbJincangyuanying.Text,
                Shuliang = Convert.ToDecimal(txtshuliang.Text),
                ID = liuzhuancard != null ? liuzhuancard.ID : 0,
                own = Tools.CurrentUser.user.YHBH,
                ShippingMark = cmbmoban.Text,
                Unit = cmbdanwei.Text,
                MaShu = txtmashu.Text.TryToInt(),
                FrontOrBack = cmbfrontorblack.Text,
                Remarlers = txtRemarkers.Text,
                MachineID = txtMachineID.Text,
                IsArrangementProduced = this.liuzhuancard.IsArrangementProduced,
                Guige = txtguige.Text,
                ProcessDeveloper = cmbGongyizhidingren.Text,
               BaseFabricColor = TxtBaseFabricColor.Text,
               IncomingAddress = txtIncomingaddress.Text,
               SingleClothWatertight = txtDanbufangshui.Text,
               SingleClothWeight = txtdanbukezhong.Text,
               SingleClothWidth = txtdanbumenfu.Text,
               FinishedProductRequirements = txtChengpingyaoqiu.Text,
               TestMetrics = txtCeshizhibiao.Text,
               BottomClothWeight=txtdibukezhong.Text ,
               Hydraulic=txtshuiya .Text,
               Washing=txtshuixi .Text,
               MoisturePermeability=txttousi .Text,
               LatestDeliverydate=dateTimePicker1 .Value,
               UrgencyLevel=cmbLevel.Text 
           };
        }
        private List<danjumingxitable> GetResMingxi()
        {
            List<danjumingxitable> resmingxis = new List<danjumingxitable>();
            foreach (var row in gridView2.GetSelectedRows())
            {
                if (!string.IsNullOrWhiteSpace(gridView2.GetRowCellValue(row, "pingming").ToString()))
                {
                    resmingxis.Add(danjumingxis[row]);
                }
            }
            return resmingxis;
        }
        private List<liuzhuanmingxi> GetLiuzhuanmingxis()
        {
            var mingxi = new List<liuzhuanmingxi>();
            //MessageBox.Show(gridView1.GetRowCellValue(0, colGongyiYaoqiu.FieldName).ToString());
            for (int row = 0; row < gridView1.RowCount; row++)
            {
                mingxi.Add(new liuzhuanmingxi()
                {
                    Beizhu = gridView1.GetRowCellValue(row, colBeizhu.FieldName) == null ? string.Empty : gridView1.GetRowCellValue(row, colBeizhu.FieldName).ToString(),
                    CardNum = txtdanhao.Text,
                    Employee = gridView1.GetRowCellValue(row, colEmployee.FieldName) == null ? string.Empty : gridView1.GetRowCellValue(row, colEmployee.FieldName).ToString(),
                    GongyiYaoqiu = gridView1.GetRowCellValue(row, colGongyiYaoqiu.FieldName) == null ? string.Empty : gridView1.GetRowCellValue(row, colGongyiYaoqiu.FieldName).ToString(),
                    MachineID = gridView1.GetRowCellValue(row, colMachineID.FieldName) == null ? string.Empty : gridView1.GetRowCellValue(row, colMachineID.FieldName).ToString(),
                    Cishu = Convert.ToInt32(gridView1.GetRowCellValue(row, colCishu.FieldName)),
                    _date = uiDatePicker1.Value
                });
            }
            return mingxi;
        }
        private Boolean  SaveRules()
        {
            gridView1.CloseEditor();
            gridView2.CloseEditor();
            if (txtmashu.Text.ToDecimal() <= 0)
            {
                MessageBox.Show(this, "打卷码数不能小于等于0");
                return false;
            }
            // 校验信息合理性
            if (!CheckMingxi())
            { return false; }
            ///
            if (gridView2.GetSelectedRows().Length == 0)
            {
                Sunny.UI.UIMessageBox.ShowError("没有任何布料别选中！\r\n请把要开流转卡的布料选中,布料前面打勾");
                return false;
            }
            if (string.IsNullOrWhiteSpace(txtbeizhu.Text))
            {
                Sunny.UI.UIMessageBox.ShowError("请填写生产工艺要求");
                return false;
            }
            if (string.IsNullOrWhiteSpace(cmbJincangyuanying.Text))
            {
                Sunny.UI.UIMessageBox.ShowError("请选择进仓原因！");
                return false;
            }
            return true;
        }
        private void 新增ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.CloseEditor();
            if (SaveRules() == false)
            {
                return;
            }
            if (Useful != FormUseful.修改)
            {
                if (LiuzhuancardService.GetLiuzhuancardlst(x => x.CardNum == txtdanhao.Text).Count > 0)
                {
                    Sunny.UI.UIMessageBox.ShowInfo($"该流转卡号{txtdanhao.Text}已经存在！\r\n系统将重新生成单号");
                    var cardNum = BianhaoBLL.CreatDanhao(FirstLetter.流转卡, uiDatePicker1.Value, DanjuLeiXing.流转卡);
                    txtdanhao.Text = cardNum;
                    foreach (var d in danjumingxis)
                    {
                        d.danhao = txtdanhao.Text;
                    }
                }
            }
            if (IsNeedPrint)
            {
                if (Sunny.UI.UIMessageBox.ShowAsk("是否直接打印该流转卡？\r\n打印按确定，不打印按取消"))
                {
                    IsNeedPrint = false;
                    Printer(PrintModel.Print);
                }
                else
                {
                    Save();
                }
            }
           
        }
        private void Continue()
        {
            gridView2.DeleteSelectedRows();
            if (danjumingxis.Sum(x => x.chengpingmishu) > 0)
            {
                if (Sunny.UI.UIMessageBox.ShowAsk("还有剩余布料没有开具流转卡!是否继续开具流转卡\r\n继续请按确定,重新开具请按取消?"))
                {
                    txtshuliang.Text = danjumingxis.Sum(x => x.chengpingmishu).ToString();
                    txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.流转卡, uiDatePicker1.Value, DanjuLeiXing.流转卡);
                }
                else
                {
                    MainForm.mainform.CloseTab();
                }
            }
            else
            {
                if (ShowMessageBox.ShowAskBox("是否继续新增操作？") == DialogResult.Yes)
                {
                    //清空所有控件
                    InitForm();
                }
                else
                {
                    MainForm.mainform.CloseTab();
                }
            }
            IsNeedPrint = true;
        }
        private void 删除行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView2.DeleteRow(gridView1.FocusedRowHandle);
        }

        private void 添加行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            danjumingxis.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = uiDatePicker1.Value });
            gridControl2.RefreshDataSource();
        }

        private void 复制行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            rowindex = gridView2.FocusedRowHandle;
        }

        private void 粘贴行ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CopyRow.Copy<danjumingxitable>(danjumingxis, rowindex, gridView2, gridView2.FocusedRowHandle, this);
        }

        private void 配置列ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 配置列(gridView2) { formname = this.Name, Obj = new danjumingxitable() };
            fm.ShowDialog();

        }

        private void 保存样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CreateGrid.SaveGridview(this.Name, gridView2);
        }

        private void ButtonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (gridView2.FocusedRowHandle >= 0)
            {
                if (txtckmc.Text == "")
                {
                    MessageBox.Show("请先选择仓库名称", "错误", MessageBoxButtons.OK);
                    return;
                }
                var fm = new 库存选择() { StockName = txtckmc.Text };
                fm.ShowDialog();
                var i = gridView2.FocusedRowHandle;

                foreach (var pingzhong in fm.pingzhong)
                {

                    danjumingxis[i].bizhong = "人民币￥";
                    danjumingxis[i].Bianhao = pingzhong.BH;
                    danjumingxis[i].guige = pingzhong.GG;
                    danjumingxis[i].chengfeng = pingzhong.CF;
                    danjumingxis[i].pingming = pingzhong.PM;
                    danjumingxis[i].kezhong = pingzhong.KZ;
                    danjumingxis[i].menfu = pingzhong.MF;
                    danjumingxis[i].danwei = "米";
                    danjumingxis[i].ContractNum = pingzhong.ContractNum;
                    danjumingxis[i].CustomName = pingzhong.CustomName;
                    danjumingxis[i].OrderNum = pingzhong.orderNum;
                    danjumingxis[i].kuanhao = pingzhong.kuanhao;
                    danjumingxis[i].houzhengli = pingzhong.houzhengli;
                    danjumingxis[i].yanse = pingzhong.YS;
                    danjumingxis[i].Chengpingyanse = pingzhong.YS;
                    danjumingxis[i].ganghao = pingzhong.GH;
                    danjumingxis[i].chengpingjuanshu = pingzhong.JS;
                    danjumingxis[i].chengpingmishu = pingzhong.MS;
                    danjumingxis[i].Kuwei = pingzhong.Kuwei;
                    danjumingxis[i].Huahao = pingzhong.Huahao;
                    danjumingxis[i].ColorNum = pingzhong.ColorNum;
                    danjumingxis[i].CustomerColorNum = pingzhong.CustomerColorNum;
                    danjumingxis[i].CustomerPingMing = pingzhong.CustomerPingMing;
                    danjumingxis[i].rq = uiDatePicker1.Value;
                    danjumingxis[i].offerid = pingzhong.RKDH;
                    danjumingxis[i].rkdh = pingzhong.RKDH;
                    danjumingxis[i].IsHanshui = IsHanshuiModel.含税;
                    danjumingxis[i].ID = pingzhong.ID;
                    danjumingxis[i].hanshuidanjia = OrderDetailTableService.GetOneOrderDetailTable(x => x.OrderNum == pingzhong.orderNum && x.sampleNum == pingzhong.BH && x.Kuanhao == pingzhong.kuanhao
                    && x.ColorNum == pingzhong.ColorNum && x.color == pingzhong.YS && x.Huahao == pingzhong.Huahao).price;
                    danjumingxis[i].hanshuiheji = danjumingxis[i].hanshuidanjia * pingzhong.MS;
                    i++;
                    if (i == danjumingxis.Count - 1)
                        for (int j = 0; j < 30; j++)
                        {
                            danjumingxis.Add(new danjumingxitable() { danhao = txtdanhao.Text, rq = Convert.ToDateTime(uiDatePicker1.Text) });
                        }
                }
                var mingxi = danjumingxis[0];
                txtkezhong.Text = mingxi.kezhong;
                txtpingming.Text = mingxi.pingming;
                txtyanse.Text = mingxi.yanse;
                txtmenfu.Text = mingxi.menfu;
                txtguige.Text = mingxi.guige;
                txtshuliang.Text = danjumingxis.Sum(x => x.chengpingmishu).ToString();
                gridControl2.RefreshDataSource();
                gridView2.CloseEditor();
                //自动加载工艺();
            }
        }

        private void txtckmc_ButtonClick(object sender, EventArgs e)
        {
            var fm = new 仓库选择();
            fm.ShowDialog();
            txtckmc.Text = fm.stock.mingcheng;
        }

        private void 选择布料ToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ButtonEdit1_ButtonClick(null, null);
        }

        private void txtkehu_ButtonClick(object sender, EventArgs e)
        {
            var fm = new 客户选择() { linkman = new LXR() { ZJC = "", MC = "" } };
            fm.ShowDialog();
            if (!string.IsNullOrEmpty(fm.linkman.MC))
            {
                txtkehu.Text = fm.linkman.MC;
                txtRemarkers.Text = fm.linkman.bz;
            }
        }

        private void gridView2_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            txtshuliang.Text = danjumingxis.Sum(x => x.chengpingmishu).ToString();
        }

        private void 复制单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.Focus();
            SendKeys.Send("^c");
        }

        private void 粘贴单元格ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            gridView1.Focus();
            SendKeys.Send("^v");
        }

        private void gridView2_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            try
            {
                decimal total = 0;
                foreach (var row in gridView2.GetSelectedRows())
                {
                    total += gridView2.GetRowCellValue(row, "chengpingmishu").TryToDecmial();
                }
                txtshuliang.Text = total.ToString();
                if (gridView2.GetSelectedRows().Length > 0)
                {
                    txtpingming.Text = gridView2.GetRowCellValue(gridView2.GetSelectedRows()[0], "pingming").ToString();
                    txtguige.Text = gridView2.GetRowCellValue(gridView2.GetSelectedRows()[0], "guige").ToString();
                    //txtmenfu.Text = gridView2.GetRowCellValue(gridView2.GetSelectedRows()[0], "menfu").ToString();
                    //txtkezhong.Text = gridView2.GetRowCellValue(gridView2.GetSelectedRows()[0], "kezhong").ToString();
                    txtyanse.Text = gridView2.GetRowCellValue(gridView2.GetSelectedRows()[0], "yanse").ToString();
                   // 自动加载工艺();
                }
                if (gridView2.GetSelectedRows().Length == danjumingxis.Count)
                {
                    SelectIndex = gridView2.GetSelectedRows().ToList();
                }
                else
                {
                    if (gridView2.GetSelectedRows().Length == 0)
                    {
                        SelectIndex.Clear();
                    }
                    else
                    {
                        if (gridView2.IsRowSelected(gridView2.FocusedRowHandle))
                        {
                            SelectIndex.Add(gridView2.FocusedRowHandle);
                        }
                        else
                        {
                            if (SelectIndex.Where(x => x == gridView2.FocusedRowHandle).ToList().Count > 0)
                            {
                                SelectIndex.Remove(gridView2.FocusedRowHandle);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void 自动加载工艺()
        {
            var liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.Customer == txtkehu.Text && x.Pingming == txtpingming.Text && x.Color == txtyanse.Text);
            if (string.IsNullOrWhiteSpace(liuzhuancard.Beizhu))
            {
                liuzhuancard = LiuzhuancardService.GetOneLiuzhuancard(x => x.Customer == txtkehu.Text && x.Pingming == txtpingming.Text);
                if (!string.IsNullOrEmpty(liuzhuancard.Beizhu))
                {
                    txtbeizhu.Text = liuzhuancard.Beizhu;
                }

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //uiContextMenuStrip1.Items.Clear();
            //var liuzhuancard = LiuzhuancardService.GetLiuzhuancardlst(x => x.Customer == txtkehu.Text && x.Pingming == txtpingming.Text );
            //foreach (var liu in liuzhuancard.Select (x=>x.Beizhu ).Distinct ())
            //{
            //    ToolStripMenuItem item = new ToolStripMenuItem(liu);
            //    item.Click += Item_Click;
            //    uiContextMenuStrip1.Items.Add(item);
            //}
            //uiButton1.ShowContextMenuStrip(uiContextMenuStrip1, 0, uiButton1.Height);
            var fm = new 历史工艺() { CustomerName = txtkehu.Text, Pingming = txtpingming.Text };
            fm.ShowDialog();
            if (!string.IsNullOrEmpty(fm.gongyimingcheng))
            {
                txtbeizhu.Text = fm.gongyimingcheng;
                liuzhuangkamingxi = fm.liuzhuangkamingxi;
                gridControl1.DataSource = liuzhuangkamingxi;
                gridControl1.RefreshDataSource();
                if (liuzhuangkamingxi != null && liuzhuangkamingxi.Count > 0)
                {
                    var card = Connect.dbcontext.Queryable<Liuzhuancard>().First(x => x.CardNum == liuzhuangkamingxi[0].CardNum);
                    if(card!=null)
                    {
                        cmbfrontorblack.Text = card.FrontOrBack;
                        TxtBaseFabricColor.Text = card.BaseFabricColor;
                        txtRemarkers.Text = card.Remarlers;
                        txtCeshizhibiao.Text = card.TestMetrics;
                        txtChengpingyaoqiu.Text = card.FinishedProductRequirements;
                        txtdanbumenfu.Text = card.SingleClothWidth;
                        txtdanbukezhong.Text = card.SingleClothWeight;
                        txtDanbufangshui.Text = card.SingleClothWatertight;
                        txtdibukezhong.Text = card.BottomClothWeight;
                        txtshuixi.Text = card.Washing;
                        txtshuiya.Text = card.Hydraulic;
                        txttousi.Text = card.MoisturePermeability;
                        txtkezhong.Text = card.Kezhong;
                        txtmenfu.Text = card.Menfu; 
                    }
                }
            }
        }
        private void Item_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = (ToolStripMenuItem)sender;
            txtbeizhu.Text = item.Text;
            var gongyis = item.Text.Split("+");
            liuzhuangkamingxi.Clear();
            foreach (var g in gongyis)
            {
                if (!string.IsNullOrEmpty(g))
                {
                    liuzhuangkamingxi.Add(new liuzhuanmingxi() { CardNum = txtdanhao.Text, Cishu = 1, GongyiYaoqiu = g, _date = uiDatePicker1.Value });
                }
            }
            gridControl1.RefreshDataSource();
        }

        private void txtkehu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var fm = new 客户选择() { linkman = new LXR() { ZJC = txtkehu.Text, MC = "" } };
                fm.ShowDialog();
                if (!string.IsNullOrEmpty(fm.linkman.MC))
                {
                    txtkehu.Text = fm.linkman.MC;
                    txtRemarkers.Text = fm.linkman.bz;
                }
            }
        }
        private void txtCkmc_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                var fm = new 客户选择() { linkman = new LXR() { ZJC = txtkehu.Text, MC = "" } };
                fm.ShowDialog();
                if (!string.IsNullOrEmpty(fm.linkman.MC))
                {
                    txtkehu.Text = fm.linkman.MC;
                    txtRemarkers.Text = fm.linkman.bz;
                }
            }
        }

        private void 加载入库单ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 入库单选择();
            fm.ShowDialog();
            int i = gridView2.FocusedRowHandle;
            foreach (var m in fm.resMingxiList)
            {
                m.danhao = txtdanhao.Text;
                m.rq = uiDatePicker1.Value;
                danjumingxis[i] = m;
                i++;
            }
            gridControl2.RefreshDataSource();
            if (fm.resMingxiList.Count > 0)
            {
                txtckmc.Text = "收货库";
                txtguige.Text = fm.resMingxiList[0].guige;
                txtkehu.Text = fm.resMingxiList[0].CustomName;
                var customer = Connect.dbcontext.Queryable<LXR>().First(x => x.MC == txtkehu.Text);
                if (customer != null)
                {
                    txtRemarkers.Text = customer.bz;
                }
                //txtkezhong.Text = fm.resMingxiList[0].kezhong;
                //txtmenfu.Text = fm.resMingxiList[0].menfu;
                txtpingming.Text = fm.resMingxiList[0].pingming;
                txtshuliang.Text = fm.resMingxiList.Sum(x => x.chengpingmishu).ToString();
                txtyanse.Text = fm.resMingxiList[0].yanse;
            }
        }

        private void uiDatePicker1_ValueChanged(object sender, DateTime value)
        {
            if (Useful == FormUseful.新增)
            {
                txtdanhao.Text = BianhaoBLL.CreatDanhao(DanjuLeiXing.流转卡, uiDatePicker1.Value, FirstLetter.流转卡);
            }
            if (Useful == FormUseful.复制)
            {
                txtdanhao.Text = BianhaoBLL.CreatDanhao(FirstLetter.流转卡, uiDatePicker1.Value, DanjuLeiXing.流转卡);
            }
        }

        private void 历史备注ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fm = new 历史备注() { CustomerName = txtkehu.Text, Pingming = txtpingming.Text };
            fm.ShowDialog();
            gridView1.SetRowCellValue(gridView1.FocusedRowHandle, "Beizhu", fm.Beizhu);

        }

        private void RawBtn_Click(object sender, EventArgs e)
        {
            SelectHelper.SelectRawMaterial(gridView3, gridControl3);
        }

        private void 设为默认样式ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SettingService.Update(new Model.Setting() { formname = "", settingname = "流转卡样式", settingValue = 打ToolStripMenuItem.Text });
        }
    }
}
